package com.szj.coroutine.project.jvm.blog5


import com.szj.coroutine.project.jvm.util.printlnCC
import kotlinx.coroutines.*
import kotlin.coroutines.*

/*
 * 作者: 史大拿
 * 时间: 2023/2/22$ 14:35$
 */

// TODO =============== suspendCancellableCoroutine 小细节1 ================
//private suspend fun test() = suspendCancellableCoroutine<String> {
//    printlnCC("打印状态1", it)
//    it.cancel()
//    printlnCC("打印状态2", it)
//    it.invokeOnCancellation { throwable ->
//        println("close ${throwable?.message}")
//    }
//}
//
//fun main() = runBlocking<Unit> {
//    println("main start")
//
//    kotlin.runCatching { test() }
//        .onSuccess {
//            println("onSuccess:$it")
//        }.onFailure {
//            println("onFailure:${it.message}")
//        }
//    println("main end")
//}


//// TODO =============== suspendCancellableCoroutine 小细节2 ================
import kotlinx.coroutines.*

suspend fun mySuspendFunction() =
    suspendCancellableCoroutine<String> { continuation -> // TODO 协程2
        val scope = CoroutineScope(EmptyCoroutineContext)
        val job = scope.launch {
            delay(1000) // 1s后才会恢复
            printlnCC("状态1", continuation)
            continuation.resume("Done")
            printlnCC("状态2", continuation)
        }

        continuation.invokeOnCancellation { // 还没来得及恢复，就已经cancel了所以会执行这里
            println("Cancellation")
            job.cancel()
        }
    }

fun main() = runBlocking {
    val job = launch {// TODO 协程1
        val result = mySuspendFunction()
        println(result)
    }
    delay(500) // 0.5s后cancel
    job.cancel() // cancel掉协程1后，协程2也会被cancel掉
}

